<?php
/**
* 定时任务：校验用户领取的任务是否超时，超时则关闭
*/
namespace app\common\command;
use think\Controller;
use think\Request;
use think\Db;


use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;

use app\api\validate\CheckValidate;
use app\api\model\TelCode;
use app\api\model\MemberTmp;
use app\api\model\Member;
use app\api\model\Base;

class closeTaskRecord extends Command
{
    protected function configure()
    {
        $this->setName('closeTaskRecord')->setDescription('Say Hello');
    }

    protected function execute(Input $input, Output $output)
    {
        $sql = "select  tr.id, tr.task_id, tr.created, tt.effective_time from sy_task_record tr left join sy_task t on t.id = tr.task_id left join sy_task_type tt on t.type_id = tt.id where tr.status = 1 and (unix_timestamp(now()) - tr.created) >= (tt.effective_time * 60)";
        $data = Db::query($sql);
        $ids = [];
        $task_ids = [];
        foreach ($data as $k=>$v){
            $ids[$k] = $v['id'];
            $task_ids[$k] = $v['task_id'];
        }
        $list = Db::name('task_record')->where([['status', '=', 1], ['id', 'in', $ids]])->select();
        
        if(!empty($ids)){
            Db::startTrans();
            $close_info = '任务超时自动关闭';
            $ret = Db::name('task_record')->where([['status', '=', 1], ['id', 'in', $ids]])->update(['status'=>-1, 'close_info'=>$close_info,'op_time'=>time()]);
            if(!$ret){
                Db::rollback();
                $output->writeln(date("Y-m-d H:i:s")."任务超时自动关闭失败1");
                return false;
            }
            $flag = true;
            foreach($task_ids as $k=>$v){
                $sql = "update sy_task set surplus_num = surplus_num + 1, received_num = received_num - 1  where id = $v";
                $ret = Db::execute($sql);
                if(!$ret){
                    $flag = false;
                    break;
                }
            }
            
            if(!$flag){
                Db::rollback();
                $output->writeln(date("Y-m-d H:i:s")."任务超时自动关闭失败2");
            }
            
            Db::commit();
            $output->writeln(date("Y-m-d H:i:s")."任务超时自动关闭成功");
        }
        $output->writeln(date("Y-m-d H:i:s")."无任务超时自动关闭");
        return true;
        
        
    }

    
    /**
    * 重置每日收入收益
    */
    
    
    /**
    * 会员是否是新用户，优质客户
    */
}
